package com.handle;

import com.config.Config;
import com.message.constant.Host;
import com.message.register.RpcRegisterRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

/**
 * @author linyu.dai
 * @project rpc
 * @description
 * @creat 2022/11/27 16:54:55
 */
@Slf4j
@ChannelHandler.Sharable
public class DefaultHandle extends ChannelInboundHandlerAdapter {

    private static final String SERVER_NAME = Config.get("rpc.application.name");

    private static final Integer PORT = Integer.valueOf(Config.get("rpc.server.port"));

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        RpcRegisterRequest rpcRegisterRequest = new RpcRegisterRequest();
        //获取本机的信息
        InetAddress address = InetAddress.getLocalHost();
        rpcRegisterRequest.setApplicationName(SERVER_NAME);
        //获取service的相关信息
        rpcRegisterRequest.setHost(new Host(PORT,address.getHostAddress()));
        ctx.channel().writeAndFlush(rpcRegisterRequest);
        super.channelActive(ctx);
    }

    //连接异常断开时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("已经异常断开异常是:{}", cause.getMessage());
    }
}